<template>
  <initVanta 
    :color="vantaData.hexToNumber(selectedColor)" 
    :effect="selectedEffect"
    ref="vantaBg"
  />
  <div>
    <div class="content-overlay">
      <div class="header">
        <backButton/>
      </div>
      <div class="title">
        <h1>Function Plugins Market</h1>
        <div class="search-container">
          <el-input 
            v-model="searchKeyword" 
            placeholder="Search..."
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>

          <el-select 
            v-model="selectedCategory" 
            placeholder="选择分类" 
            class="category-select"
            clearable
          >
            <el-option 
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </div>
      </div>
      <div class="main-content">
        <!-- 新增分类结构 -->
        <div 
          v-for="([category, plugins], categoryIndex) in Object.entries(groupedPlugins)" 
          :key="category"
          class="category-group category-animate"
          :style="{ animationDelay: categoryIndex * 0.2 + 's' }"
          v-show="shouldShowCategory(category)"
        >
          <div class="category-header category-title-animate" :style="{ animationDelay: categoryIndex * 0.2 + 0.1 + 's' }">
            <h2>{{ category }}</h2>
          </div>
          <div class="card-container">
            <card-temp
              v-for="(plugin, pluginIndex) in plugins"
              :key="plugin.id"
              :id="plugin.id"
              :name="plugin.name"
              :description="plugin.description"
              :category="plugin.category"
              :subtitle="plugin.description"
              :showDelete="false"
              :isDownloading="downloadingPlugins.has(plugin.id)"
              class="plugin-card-animate"
              :style="{ animationDelay: (categoryIndex * 0.2 + pluginIndex * 0.1 + 0.3) + 's' }"
              @click="addPlugin(plugin)"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import initVanta from '../components/initVanta.vue';
import { ref, onMounted, computed } from 'vue';
import CardTemp from '../components/cardTemp.vue';
import BackButton from "../components/backButton.vue";
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { Plugin } from '../store/PluginInterface';
import router from '../router';
import { Search } from '@element-plus/icons-vue';
import backButton from '../../src/components/backButton.vue';
import { useVanta } from '../components/useVanta';

const { selectedColor, selectedEffect, hexToNumber } = useVanta();

const vantaData = useVanta();

const searchKeyword = ref('');
const selectedCategory = ref('');
const downloadingPlugins = ref<Set<string>>(new Set());
const categories = computed(() => {
  return Array.from(new Set(plugins.value.map(p => p.category)));
});

const filteredPlugins = computed(() => {
  return plugins.value.filter(plugin => {
    const matchesKeyword = plugin.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      plugin.description.toLowerCase().includes(searchKeyword.value.toLowerCase());
    const matchesCategory = !selectedCategory.value || 
      plugin.category === selectedCategory.value;
    return matchesKeyword && matchesCategory;
  });
});

declare const electronAPI: any;

const baseUrl = 'http://10.169.128.20/files/plugins';

const plugins = ref<Plugin[]>([]);

const groupedPlugins = computed(() => {
  return filteredPlugins.value.reduce((groups: Record<string, Plugin[]>, plugin) => {
    const category = String(plugin.category) || '未分类';
    if (!groups[category]) {
      groups[category] = [];
    }
    groups[category].push(plugin);
    return groups;
  }, {} as Record<string, Plugin[]>);
});

// 从服务器获取插件列表
const fetchPlugins = async () => {
  try {
    const response = await axios.get(`http://localhost:3005/pl`);
    if (Array.isArray(response.data)) {
      plugins.value = response.data.map((plugin: any) => ({
        id: plugin.id,
        name: plugin.name,
        category: plugin.category,
        version: plugin.version,
        downloadUrl: `${baseUrl}/${plugin.id}.zip`,
        description: plugin.description,
      }));
    } else {
      console.error('服务器返回的数据不是数组:', response.data);
    }
  } catch (error) {
    console.error('获取插件列表失败:', error);
    ElMessage.error('获取插件列表失败');
  }
};

// 添加插件到主界面
const addPlugin = async (plugin: Plugin) => {
  try {
    // 检查是否正在下载
    if (downloadingPlugins.value.has(plugin.id)) {
      ElMessage.warning('该插件正在下载中，请稍候...');
      return;
    }

    // 检查下载链接是否存在
    if (!plugin.downloadUrl) {
      ElMessage.warning('插件下载链接缺失');
      return;
    }

    // 检查插件是否已存在
    const userPlugins = JSON.parse(localStorage.getItem('userPlugins') || '[]');
    if (userPlugins.some((p: Plugin) => p.id === plugin.id)) {
      ElMessage.warning('该插件已存在');
      return;
    }

    // 添加到下载状态
    downloadingPlugins.value.add(plugin.id);

    // 显示下载开始消息
    ElMessage.info({
      message: `正在下载插件: ${plugin.name}...`,
      duration: 2000
    });

    // 添加调试信息
    console.log('下载插件:', plugin.id, 'URL:', plugin.downloadUrl);

    // 下载插件
    const result = await electronAPI.downloadPlugin(plugin.id, `http://localhost:3005/download/${plugin.id}`);
    if (!result.success) {
      throw new Error(result.error || '未知错误');
    }
    
    // 显示下载成功消息
    ElMessage.success({
      message: `插件 ${plugin.name} 下载成功！`,
      duration: 3000
    });
    
    // 将插件信息保存到 localStorage
    const updatedUserPlugins = JSON.parse(localStorage.getItem('userPlugins') || '[]');
    updatedUserPlugins.push(plugin);
    localStorage.setItem('userPlugins', JSON.stringify(updatedUserPlugins));
    
    ElMessage.success({
      message: '插件添加成功，正在跳转到主页面...',
      duration: 2000
    });
    
    // 延迟跳转，让用户看到成功消息
    setTimeout(() => {
      router.push('/');
    }, 1500);
    
  } catch (error) {
    console.error('添加插件失败:', error);
    ElMessage.error({
      message: `下载失败: ${error instanceof Error ? error.message : '未知错误'}`,
      duration: 4000
    });
  } finally {
    // 无论成功还是失败，都要从下载状态中移除
    downloadingPlugins.value.delete(plugin.id);
  }
};

// 分类显示判断方法
const shouldShowCategory = (category: string) => {
  return !selectedCategory.value || category === selectedCategory.value;
};

onMounted(() => {
  fetchPlugins();
});
</script>

<style scoped>
.content-overlay {
  position: relative; /* 确保内容层叠在 Vanta.js 背景之上 */
  z-index: 1; /* 高于 Vanta.js 背景 */
  display: flex; /* 启用 Flexbox 布局 */
  justify-content: flex-start; /* 靠左放置 */
  padding-top: 0px; /* 或者其他你需要的值，以便内容不紧贴顶部 */
  padding-left: 80px;
  padding-right: 80px; /* 新增：确保右侧也有相同的内边距 */
  flex-direction: column; /* 垂直排列子元素 */
  height: 100vh; /* 使内容覆盖整个视口高度 */
  overflow: hidden; /* 防止出现双滚动条 */
}

.header {
  display: flex;
  justify-content: flex-start;
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: -20px; /* 底部间距 */
  margin-top: -8px;
  width: 100%; /* 确保 header 占据整个宽度 */
  position: sticky; /* 使 header 保持在顶部 */
  top: 0;
  z-index: 10; /* 确保在其他元素之上 */
  background: transparent; /* 保持背景透明 */
}

.title {
  position: sticky;
  top: 40px; /* 调整标题固定的位置，在header下方 */
  z-index: 9; /* 低于header但高于内容 */
  background: transparent; /* 保持背景透明 */
  padding-bottom: 10px; /* 添加一些底部间距 */
}

.main-content {
  flex: 1; /* 使主要内容占据剩余空间 */
  margin-top: -20px;
  overflow-y: auto; /* 只在主内容区域添加滚动 */
  height: calc(100vh - 200px); /* 减去header和title的高度 */
  padding-top: 20px; /* 添加顶部间距 */
  padding-right: 0; /* 移除右侧内边距，使滚动条紧贴右侧边缘 */
  mask-image: linear-gradient(to bottom, transparent 0, black 20px); /* 创建顶部渐变遮罩效果 */
  -webkit-mask-image: linear-gradient(to bottom, transparent 0, black 20px);
  /* 自定义滚动条样式 */
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: rgba(129, 110, 216, 0.5) transparent; /* Firefox */
}

/* 自定义滚动条样式 - Webkit浏览器 */
.main-content::-webkit-scrollbar {
  width: 6px; /* 滚动条宽度 */
}

.main-content::-webkit-scrollbar-track {
  background: transparent; /* 滚动条轨道背景 */
}

.main-content::-webkit-scrollbar-thumb {
  background-color: rgba(129, 110, 216, 0.5); /* 滚动条颜色，使用紫色主题色 */
  border-radius: 10px; /* 圆角 */
  border: 2px solid transparent; /* 边框 */
  background-clip: content-box; /* 背景裁剪到内容框 */
}

.main-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(129, 110, 216, 0.8); /* 悬停时的颜色 */
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 60px;
  justify-content: flex-start;
  margin-bottom: 20px;
  row-gap: 0px;
}

.category-group {
  margin-bottom: -60px;
}

.category-header {
  margin: 0.5rem 0;
  padding-left: 1rem;
  border-left: 4px solid #a970ff;
  text-align: left;
}

.search-container {
  display: flex;
  gap: 15px;
  margin: 20px 0;
  padding: 0;
}

.search-input {
  flex: 0 0 200px; 
  max-width: 300px;
}

.search-input:hover {
  border: 1px solid rgb(44, 29, 29);
  box-shadow: 0px 0px 20px -5px;
}

.search-input:active {
  transform: scale(0.99);
}

.search-input:focus {
  border: 2px solid grey;
}

.category-select {
  width: 100px;
}

/* 页面加载动画样式类 */
.category-animate {
  animation: fadeInUp 0.8s ease-out both;
}

.category-title-animate {
  animation: slideInFromLeft 0.6s ease-out both;
}

.plugin-card-animate {
  animation: fadeInUp 0.6s ease-out both;
}

/* 页面加载动画关键帧定义 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInFromLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>